package com.bfly.mall.wechat.common;

import com.alibaba.fastjson.JSONObject;
import com.bfly.common.json.JsonUtil;
import com.bfly.core.base.entity.RemoteResponse;
import com.bfly.core.cache.EhCacheUtil;
import com.bfly.core.enums.SysError;
import com.bfly.core.exception.ServiceResponseException;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.client.methods.HttpGet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 微信小程序API接口
 *
 * @author 长沙商脉科技有限公司
 * @date 2020/5/9 11:40
 */
public class WeChatAPi {

    private static Logger logger = LoggerFactory.getLogger(WeChatAPi.class);

    /**
     * 获取小程序全局唯一后台接口调用凭据（access_token）。调用绝大多数后台接口时都需使用 access_token
     *
     * @author 长沙商脉科技有限公司
     * @date 2020/5/9 11:43
     */
    public static final String ACCESS_TOKEN = "https://api.weixin.qq.com/cgi-bin/token";

    /**
     * 获取小程序全局唯一后台接口调用凭据
     *
     * @author 长沙商脉科技有限公司
     * @date 2020/11/12 15:07
     */
    public static String getAccessToken(String appId, String appSecret) {
        synchronized (WeChatAPi.class) {
            String token = EhCacheUtil.getData(EhCacheUtil.WE_CHAT_ACCESS_TOKEN_CACHE, appId, String.class);
            if (StringUtils.isBlank(token)) {
                // 缓存不存在则重新生成并放入缓存
                RemoteResponse response;
                String url = WeChatAPi.ACCESS_TOKEN.concat("?grant_type=client_credential")
                        .concat("&appid=" + appId)
                        .concat("&secret=" + appSecret);
                try {
                    HttpGet get = new HttpGet(url);
                    response = WeChatHttpUtil.weChatHttpRequest(get);
                } catch (Exception e) {
                    throw new ServiceResponseException(SysError.REMOTE_ERROR);
                }
                WeChatAssert.checkResponse(response);
                JSONObject json = JsonUtil.parse(response.getBody(), JSONObject.class);
                token = json.getString("access_token");
                EhCacheUtil.setData(EhCacheUtil.WE_CHAT_ACCESS_TOKEN_CACHE, appId, token);
            }
            return token;
        }
    }
}